package com.cloud.apis.websocket;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/4/25
 */
@Component
@Slf4j
@ServerEndpoint("/webSocket/{userId}")
public class WebSocketServe {
    private Session session;
    private Long userId;
    private static CopyOnWriteArraySet<WebSocketServe> webSocketServeSet = new CopyOnWriteArraySet<>();
    public WebSocketServe(){
        log.info("【WebSocketServe】");
    }
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") Long userId) {
        this.session = session;
        this.userId =userId;
        webSocketServeSet.add(this);
    }
    @OnClose
    public void onClose() {
        webSocketServeSet.remove(this);
    }
    @OnMessage
    public void onMessage(String message) {

    }

    public void sendMessage(Long targetUserId)  {
        for (WebSocketServe webSocketServe: webSocketServeSet) {
            if (webSocketServe.userId.equals(targetUserId)) {
                try{
                    webSocketServe.session.getBasicRemote().sendText("new message");
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

        }
    }
    public void sendApprovalMessage(Long targetUserId)  {
        for (WebSocketServe webSocketServe: webSocketServeSet) {
            if (webSocketServe.userId.equals(targetUserId)) {
                try{
                    webSocketServe.session.getBasicRemote().sendText("new approval");
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

        }
    }
    public void sendMessage(Long targetUserId,String message)  {
        for (WebSocketServe webSocketServe: webSocketServeSet) {
            if (webSocketServe.userId.equals(targetUserId)) {
                try{
                    webSocketServe.session.getBasicRemote().sendText(message);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

        }
    }
}
